package com.swim.cron;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.swim.common.utils.DateUtil;
import com.swim.natatoriuminfo.entity.ClickStats;
import com.swim.natatoriuminfo.entity.NatatoriumInfo;
import com.swim.natatoriuminfo.service.ClickStatsService;
import com.swim.natatoriuminfo.service.NatatoriumInfoService;
import com.swim.phonenumprivacy.entity.AxnDTO;
import com.swim.phonenumprivacy.service.BindAxnExtensionService;
import com.swim.phonenumprivacy.service.StringStorageUtil;

/**
 * @description : 系统定时器总入口
 * @author : 刘军武
 * @version : 1.0
 * @create : 2019年12月11日 下午6:15:46
 **/

@Component
@EnableScheduling
public class SwimCronTasks {

	@Autowired
	private NatatoriumInfoService natatoriumInfoService;

	@Autowired
	private ClickStatsService clickStatsService;

	@Autowired
	private BindAxnExtensionService bindAxnExtensionService;
	
	/**
	 * @Scheduled(cron="0/15 * * * * ?") //每15秒执行一次 
	 * @Scheduled(cron="0 0 0 * * ?") //每天凌晨0点执行一次 
	 * @Scheduled(cron="0 0 2 * * ?") //每天凌晨2点执行一次 
	 * @Scheduled(cron="0 0 4 * * ?") //每天凌晨4点执行一次 
	 * @Scheduled(cron="0 0 6 * * ?") //每天凌晨6点执行一次
	 * 
	 */

	
	/**
	 * 给游泳馆生成访问数据(每天凌晨2点执行一次)
	 */
	@Scheduled(cron = "0 0 2 * * ?") // 每天凌晨2点执行一次
//	  @Scheduled(cron="0/30 * * * * ?")   //每30秒执行一次
	public void generateClickStatsData() {
		// 查询所有游泳馆数据
		List<NatatoriumInfo> natatoriumInfoList = natatoriumInfoService.findList(new NatatoriumInfo());
		if (CollectionUtils.isNotEmpty(natatoriumInfoList)) {
			String[] strs = {};
			for (NatatoriumInfo natatoriumInfo : natatoriumInfoList) {
				if (StringUtils.isNotEmpty(natatoriumInfo.getIncreaseDailyVisits())) {
					strs = natatoriumInfo.getIncreaseDailyVisits().split("-");
					// 获取需要生成访问数据数量
					Integer addNum = getRandomInt(Integer.parseInt(strs[0]), Integer.parseInt(strs[1]));
					List<ClickStats> addClickStatsList = new ArrayList<ClickStats>();
					for (int i = 0; i < addNum; i++) {
						ClickStats clickStats = new ClickStats();
						clickStats.setNatatoriumInfoId(natatoriumInfo.getId());
						clickStats.setMac(randomMacAddress());
						clickStats.setIp(getRandomIp());
						clickStats.setCreateDate(randomDate());
						addClickStatsList.add(clickStats);
					}
					if(CollectionUtils.isNotEmpty(addClickStatsList)) {
						// 批量新增访问数据
						clickStatsService.insertBatch(addClickStatsList);
					}
				}
			}
		}
	}

	/**
	 * 获取min-max之间的随机整数
	 * @param min
	 * @param max
	 * @return
	 */
	private Integer getRandomInt(Integer min, Integer max) {
		// 取x到y之间的随机整数
		int n = max - min;
		double m = Math.random() * n;
		return (int) m + min;
	}

	/**
	 * 随机生成mac地址
	 * 
	 * @param min
	 * @param max
	 * @return
	 */
	private String randomMacAddress() {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < 6; i++) {
			if (sb.length() > 0) {
				sb.append(":");
			}
			Random random = new Random();
			int val = random.nextInt(256);
			String element = Integer.toHexString(val);
			if (element.length() < 2) {
				sb.append(0);
			}
			sb.append(element);
		}
		return sb.toString();
	}

	/**
	 * 获取一个随机IP
	 */
	public String getRandomIp() {
		// 指定 IP 范围
		int[][] range = { { 607649792, 608174079 }, // 36.56.0.0-36.63.255.255
				{ 1038614528, 1039007743 }, // 61.232.0.0-61.237.255.255
				{ 1783627776, 1784676351 }, // 106.80.0.0-106.95.255.255
				{ 2035023872, 2035154943 }, // 121.76.0.0-121.77.255.255
				{ 2078801920, 2079064063 }, // 123.232.0.0-123.235.255.255
				{ -1950089216, -1948778497 }, // 139.196.0.0-139.215.255.255
				{ -1425539072, -1425014785 }, // 171.8.0.0-171.15.255.255
				{ -1236271104, -1235419137 }, // 182.80.0.0-182.92.255.255
				{ -770113536, -768606209 }, // 210.25.0.0-210.47.255.255
				{ -569376768, -564133889 }, // 222.16.0.0-222.95.255.255
		};
		Random random = new Random();
		int index = random.nextInt(10);
		String ip = num2ip(range[index][0] + random.nextInt(range[index][1] - range[index][0]));
		return ip;
	}

	/*
	 * 将十进制转换成IP地址
	 */
	public static String num2ip(int ip) {
		int[] b = new int[4];
		b[0] = (ip >> 24) & 0xff;
		b[1] = (ip >> 16) & 0xff;
		b[2] = (ip >> 8) & 0xff;
		b[3] = ip & 0xff;
		// 拼接 IP
		String x = b[0] + "." + b[1] + "." + b[2] + "." + b[3];
		return x;
	}

	/**
	 * 生成当天的随机时间
	 * 
	 * @return Date
	 */
	public static Date randomDate() {
		Date start = DateUtil.getStartTimeOfDay();// 当天开始日期
		Date end = DateUtil.getEndTimeOfDay();// 当天结束日期
		try {
			// getTime()表示返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
			if (start.getTime() >= end.getTime()) {
				return null;
			}
			long date = random(start.getTime(), end.getTime());
			return new Date(date);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static long random(long begin, long end) {
		long rtn = begin + (long) (Math.random() * (end - begin));
		// 如果返回的是开始时间和结束时间，则递归调用本函数查找随机值
		if (rtn == begin || rtn == end) {
			return random(begin, end);
		}
		return rtn;
	}
	
	
	/**
	 * 隐私号码解绑关系定时解绑
	 */
	@Scheduled(cron="0/30 * * * * ?")   //每30秒执行一次
	public void unbindAxnExtension() {
		// 获取绑定超过5分钟的隐私号码绑定关系数据
		StringStorageUtil subsIdStorageUtil = new StringStorageUtil();
		List<String> expiredIdsList = subsIdStorageUtil.getExpiredIds();
		if(CollectionUtils.isNotEmpty(expiredIdsList)) {
			for (String expiredId : expiredIdsList) {
				String[] dadas = expiredId.split("+");
				AxnDTO axnDTO = new AxnDTO();
				axnDTO.setSubsId(dadas[0]);
				axnDTO.setSecretNo(dadas[1]);
				//调用解绑方法
				bindAxnExtensionService.unbindAxnExtension(axnDTO);
			}
		}
	}
}
